//
//  KLLoginViewController.m
//  Meboo
//
//  Created by kyo on 2023/12/20.
//

#import "KLLoginViewController.h"

#import "MBLoginClickView.h"
#import "MBPageControlView.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "MBWebViewController.h"
#import "MBPhoneViewController.h"
#import <RongCloudOpenSource/RongIMKit.h>
@interface KLLoginViewController ()
<
ASAuthorizationControllerDelegate,
ASAuthorizationControllerPresentationContextProviding
>
//@property (nonatomic, strong) MBLoginClickView *loginView;
@property (nonatomic, strong) ASAuthorizationAppleIDButton *loginView;
//@property (nonatomic, strong) MBLoginPhoneView *loginPhoneView;
@property (nonatomic, strong) UIButton *loginPhoneView;
@property (nonatomic, strong) UILabel *privacyLab0;
@property (nonatomic, strong) UILabel *privacyLab1;
@property (nonatomic, strong) UILabel *privacyLab2;
@property (nonatomic, strong) UILabel *privacyLab3;

@property (nonatomic, strong) MBPageControlView *pageControlView;
@property (nonatomic, copy) NSString *identityTokenStr;

@property (nonatomic, strong) UIImageView *logoImageView;
@property (nonatomic, strong) UIButton *leftBtn;
@end

@implementation KLLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupUI];
    [[RCIM sharedRCIM] logout];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
}

#pragma mark - Private Method
- (void)agreementClick {
    MBWebViewController *webVC = [[MBWebViewController alloc] init];
    [webVC loadWithURL:[NSURL URLWithString:termsWeb]];
    webVC.titleStr = @"User Agreement";
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)itemsClick {

    MBWebViewController *webVC = [[MBWebViewController alloc] init];
    [webVC loadWithURL:[NSURL URLWithString:privacyPolicyWeb]];
    webVC.titleStr = @"Privacy Policy";
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)loginWithPhone {
    
    [self dismissViewControllerAnimated:NO completion:nil];
    [self.currentViewController.navigationController pushViewController:[MBPhoneViewController new] animated:YES];
    
}

- (void)leftAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickLogin {
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
        appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
        authorizationController.delegate = self;
        authorizationController.presentationContextProvider = self;
        [authorizationController performRequests];
    } else {
        NSLog(@"error");
    }
    /**
     埋点 code
     登陆 101
     */
    [[NSIOApiManager sharedManager] setIOWithCode:@"101" content:@"appleLogin"];
}

/// 授权成功回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
        NSData *identityToken = appleIDCredential.identityToken;
        
        // 注意：使用过授权的，可能获取不到以下三个参数，要做判空处理
        NSString *nickname = appleIDCredential.fullName.nickname;
        NSString *emailStr = appleIDCredential.email;
        if (nickname.length == 0 ) {
            if (appleIDCredential.fullName.familyName .length > 0 &&  appleIDCredential.fullName.givenName.length > 0) {
                nickname = [NSString stringWithFormat:@"%@%@",appleIDCredential.fullName.familyName, appleIDCredential.fullName.givenName];
            } else if (appleIDCredential.fullName.familyName.length > 0) {
                nickname = appleIDCredential.fullName.familyName;
            } else if (appleIDCredential.fullName.givenName.length > 0) {
                nickname = appleIDCredential.fullName.givenName;
            }
        }
        
        if (nickname.length == 0) {
            nickname = @"";
        }
        
        // 服务器验证需要使用的参数
//        self.identityTokenStr = [[NSString alloc] initWithData:identityToken encoding:NSUTF8StringEncoding];
        self.identityTokenStr = appleIDCredential.user;
        NSLog(@"");


        
        // TODO， 将用户名和 token 传给服务器做验证。
        // 注意： 非第一次授权，nickname可能为空。
//        __WeakSelf
        [[MBLoginDataManager sharedManager] loginWithIdentityTokenStr:self.identityTokenStr userName:@"" email:emailStr success:^(BOOL success) {
            AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
            [MBNotificationCenter postNotificationName:LOGIN_SENDED_NOTIFICATION object:nil];
            if (success) {
                [MBProgressHUD showSuccessMessage:@"Login Success"];
                appDelegate.window.rootViewController = [[BaseTabBarViewController alloc]init];
            } else {
                [MBProgressHUD showErrorMessage:@"Login Fail"];
            }
        }];
    } else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
        [MBNotificationCenter postNotificationName:LOGIN_SENDED_NOTIFICATION object:nil];
        // 这个获取的是iCloud记录的账号密码，需要输入框支持iOS 12 记录账号密码的新特性，如果不支持，可以忽略
        ASPasswordCredential *passwordCredential = authorization.credential;
        NSString *user = passwordCredential.user;
        NSString *password = passwordCredential.password;
        
    } else {
        [MBNotificationCenter postNotificationName:LOGIN_SENDED_NOTIFICATION object:nil];
        NSLog(@"授权信息不符");
    }
}

/// 授权失败回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    NSLog(@"Handle error：%@", error);
    NSString *errorMsg = nil;
    [MBNotificationCenter postNotificationName:LOGIN_SENDED_NOTIFICATION object:nil];
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
        default:
            break;
    }
    NSLog(@"errorMsg = %@", errorMsg);
}

/// 设置展示内容给用户的Window
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)) {
    return [UIApplication sharedApplication].windows.lastObject;
}


#pragma mark - UI
- (void)setupUI {
    
//    [self.view addSubview:self.leftBtn];
//    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(MBWidthScale(15));
//        make.top.mas_equalTo(StatusBarAndNavigationBarHeight-MBHeightScale(13)-MBHeightScale(20));
//        make.height.width.mas_equalTo(MBHeightScale(20));
//    }];
    
    [self.view addSubview:self.logoImageView];
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(MBHeightScale(100));
        make.centerX.equalTo(self.view);
        make.width.height.mas_equalTo(MBHeightScale(80));
    }];
    

    [self.view addSubview:self.loginPhoneView];
    [self.loginPhoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_centerY).offset(MBHeightScale(10));
        make.left.mas_equalTo(MBWidthScale(20));
        make.right.mas_equalTo(MBWidthScale(-20));
        make.height.mas_equalTo(MBHeightScale(60));
    }];
    
    [self.view addSubview:self.loginView];
    [self.loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.loginPhoneView.mas_top).offset(MBHeightScale(-20));
        make.left.mas_equalTo(MBWidthScale(20));
        make.right.mas_equalTo(MBWidthScale(-20));
        make.height.mas_equalTo(MBHeightScale(60));
    }];
    
    [self.view addSubview:self.privacyLab0];
    [self.privacyLab0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loginPhoneView.mas_bottom).offset(MBHeightScale(17));
        make.right.equalTo(self.view.mas_centerX).offset(-2);
    }];
    
    [self.view addSubview:self.privacyLab1];
    [self.privacyLab1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privacyLab0);
        make.left.equalTo(self.view.mas_centerX).offset(0);
    }];
    
    [self.view addSubview:self.privacyLab2];
    [self.privacyLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privacyLab0);
        make.left.equalTo(self.privacyLab1.mas_right).offset(1);
    }];
    
    [self.view addSubview:self.privacyLab3];
    [self.privacyLab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privacyLab0);
        make.left.equalTo(self.privacyLab2.mas_right).offset(1);
    }];
}

#pragma mark - Setter && Getter

//- (MBLoginClickView *)loginView {
//    if (!_loginView) {
//        _loginView = [MBLoginClickView new];
//        __WeakSelf
//        _loginView.loginBlock = ^{
//            [weakSelf clickLogin];
//        };
//    }
//    return _loginView;
//}
- (ASAuthorizationAppleIDButton *)loginView {
    if (!_loginView) {
        _loginView = [ASAuthorizationAppleIDButton buttonWithType:ASAuthorizationAppleIDButtonTypeSignIn style:ASAuthorizationAppleIDButtonStyleBlack];
        _loginView.cornerRadius = MBHeightScale(30);
        [_loginView addTarget:self action:@selector(clickLogin) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginView;
}

//- (MBLoginPhoneView *)loginPhoneView {
//    if (!_loginPhoneView) {
//        _loginPhoneView = [MBLoginPhoneView new];
//        __WeakSelf
//        _loginPhoneView.loginBlock = ^{
//            [MBNotificationCenter postNotificationName:LOGIN_SENDED_NOTIFICATION object:nil];
//            [weakSelf.navigationController pushViewController:[MBPhoneViewController new] animated:YES];
//        };
//    }
//    return _loginPhoneView;
//}
- (UIButton *)loginPhoneView {
    if (!_loginPhoneView) {
        _loginPhoneView = [UIButton leftimageAndRighttitlePatternWithImage:@"login_phone" AndMargin:MBWidthScale(6) AndTitle:@"Sign in with phone number" AndTitleFont:MBHelFontSizeScale(18) AndTitleColor:HEXS(@"22253C")];
        [_loginPhoneView addTarget:self action:@selector(loginWithPhone) forControlEvents:UIControlEventTouchUpInside];
        _loginPhoneView.backgroundColor = UIColor.whiteColor;
        _loginPhoneView.layer.cornerRadius = MBHeightScale(30);
        _loginPhoneView.layer.borderWidth = 1;
        _loginPhoneView.layer.borderColor = HEXS(@"22253C").CGColor;
    }
    return _loginPhoneView;
}

- (UILabel *)privacyLab1 {
    if (!_privacyLab1) {
        _privacyLab1 = [UILabel new];
        _privacyLab1.userInteractionEnabled = YES;
        _privacyLab1.font = MBFontSizeScale(10);
        // 下划线
        //注意: NSStrikethroughStyleAttributeName 是添加中划线,这时textStr如果是中文字符则没有效果
        NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName : [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSUnderlineColorAttributeName :HEXS(@"202323")};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"User Agreement" attributes:attribtDic];
        
        //赋值
        _privacyLab1.attributedText = attribtStr;
        
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(agreementClick)];
        
        [_privacyLab1 addGestureRecognizer:gestureRecognizer];

    }
    return _privacyLab1;
}

- (UILabel *)privacyLab3 {
    if (!_privacyLab3) {
        _privacyLab3 = [UILabel new];
        _privacyLab3.userInteractionEnabled = YES;
        _privacyLab3.font = MBFontSizeScale(10);
        // 下划线
        //注意: NSStrikethroughStyleAttributeName 是添加中划线,这时textStr如果是中文字符则没有效果
        NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName : [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSUnderlineColorAttributeName :HEXS(@"202323")};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"Privacy Items" attributes:attribtDic];
        
        //赋值
        _privacyLab3.attributedText = attribtStr;
        
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(itemsClick)];
        
        [_privacyLab3 addGestureRecognizer:gestureRecognizer];

    }
    return _privacyLab3;
}

- (UILabel *)privacyLab0 {
    if (!_privacyLab0) {
        _privacyLab0 = [UILabel new];
        _privacyLab0.text = @"By continuing, you agree to our ";
        _privacyLab0.font = MBFontSizeScale(10);
        _privacyLab0.textColor = HEXS(@"202323");
    }
    return _privacyLab0;
}

- (UILabel *)privacyLab2 {
    if (!_privacyLab2) {
        _privacyLab2 = [UILabel new];
        _privacyLab2.text = @" & ";
        _privacyLab2.font = MBFontSizeScale(10);
        _privacyLab2.textColor = HEXS(@"202323");
    }
    return _privacyLab2;
}

- (MBPageControlView *)pageControlView {
    if (!_pageControlView) {
        _pageControlView = [MBPageControlView new];
    }
    return _pageControlView;
}

- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = [UIImageView new];
        _logoImageView.image = ImageWithName(@"appLogo");
    }
    return _logoImageView;
}

- (UIButton *)leftBtn {
    if (!_leftBtn) {
        _leftBtn = [[UIButton alloc] init];
        [_leftBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_leftBtn setImage:ImageWithName(@"login_back") forState:0];
        [_leftBtn addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBtn;
}
@end
